package com.example.esp32;

import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceManager;

import android.content.ContentValues;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.shy.rockerview.MyRockerView;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;

import java.io.IOException;

import tv.danmaku.ijk.media.player.IjkMediaPlayer;


public class yg extends AppCompatActivity {
//private JoystickView joystickView;
private TextView tes,rcca,dcca,tx;
private WebView videoView;

private MqttClient client;
//    String topic = "esp";
//    private WebView videoView ;
//    String content = "我去";
//    int qos = 2;
//    String broker = "tcp://ipzhangt:1883";
//    String clientId = MqttClient.generateClientId();
    private Button button5;
    MemoryPersistence persistence = new MemoryPersistence();
    int jl,jd;
    MqttConnectOptions connOpts = new MqttConnectOptions();
private MyRockerView rockerView,rocc;
    private SurfaceView mSurfaceView;
    String url = "rtmp://121.5.160.114:1935/stream/sbss";

private Button button4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yg);
        tes=findViewById(R.id.recsc);
        rcca=findViewById(R.id.rcc);
        dcca=findViewById(R.id.dcc);

        rockerView=findViewById(R.id.roc);
        rocc=findViewById(R.id.rocc);
        button4=findViewById(R.id.button4);
        button5=findViewById(R.id.button5);
        tx=findViewById(R.id.tx);
        videoView=findViewById(R.id.webb);
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        String broker = sharedPreferences.getString("broker", "");
        String USER = sharedPreferences.getString("USER", "");
        String PAWW = sharedPreferences.getString("PAWW", "");
        String clientId = sharedPreferences.getString("clientId", "");
        String topic = sharedPreferences.getString("topic", "");
        String content = sharedPreferences.getString("content", "");
        String weburl = sharedPreferences.getString("weburl", "");

        int qos = sharedPreferences.getInt("qos",2 );
        Log.d(TAG, "onCreate: "+broker+USER+clientId+topic);
        if(broker.equals("")|USER.equals("")|PAWW.equals("")|clientId.equals("")|topic.equals("")|content.equals("")){
            Toast.makeText(yg.this,"请先在设置里正确配置摇杆",Toast.LENGTH_LONG).show();
            finish();
        }else {
        try {
            client = new MqttClient(broker, clientId, persistence);
        } catch (Exception e) {
            Toast.makeText(this, "url似乎不正确:"+e, Toast.LENGTH_LONG).show();      }}
        connOpts.setUserName(USER);
        connOpts.setPassword(PAWW.toCharArray());
        MqttClient finalClient = client;
        button5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                web("file:///android_asset/404.html");
                try {
                    finalClient.disconnect();
                    Toast.makeText(yg.this, "小车车走咯", Toast.LENGTH_LONG).show();

                } catch (MqttException e) {
                    Toast.makeText(yg.this, "你都没有呼叫小车车", Toast.LENGTH_LONG).show();
                }

            }


        });
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                web(weburl);
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        String mea = "l";
                        try {
                            // 设置回调
                            finalClient.setCallback(new SampleCallback());
                            // 建立连接
                            System.out.println("Connecting to broker: " + broker);
                            finalClient.connect(connOpts);
                            System.out.println("Connected to broker: " + broker);
                            // 订阅 topic
                            finalClient.subscribe(topic, qos);
                            System.out.println("Subscribed to topic: " + topic);
                            // 发布消息
                            MqttMessage message = new MqttMessage(content.getBytes());
                            message.setQos(qos);

                            finalClient.publish(topic, message);
                            System.out.println("Message published");
//                    finalClient.disconnect();
                            System.out.println("Disconnected");
//                    finalClient.close();
                        } catch (MqttException me) {
                            mea= String.valueOf(me);

                        }
                        String finalMea = mea;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if(finalMea.equals("l")){
                                Toast.makeText(yg.this, "小车车来咯", Toast.LENGTH_LONG).show();}
                                else{
                                    Toast.makeText(yg.this, "小车车不见了", Toast.LENGTH_LONG).show();

                                }
                            }
                        });
                    }
                }.start();


            }
        });
        MqttClient finalClient1 = client;
        rocc.setOnDistanceLevelListener(new MyRockerView.OnDistanceLevelListener() {
            @Override
            public void onDistanceLevel(int level) {

                jl=level;
                tes.setText(""+level);
            }
        });
        rockerView.setOnShakeListener(MyRockerView.DirectionMode.DIRECTION_8, new MyRockerView.OnShakeListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void direction(MyRockerView.Direction direction) {
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        String a= String.valueOf(direction);
                        String ss = "null";
                        try {
                            MqttMessage message = new MqttMessage(a.getBytes());
                            message.setQos(qos);

                            finalClient.publish(topic, message);
                        } catch (MqttException e) {
                            ss=String.valueOf(e);

                        }
                        String finalSs = ss;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tx.setText(finalSs);
                            }
                        });
                    }
                }.start();
               rcca.setText(""+direction);
            }

            @Override
            public void onFinish() {

            }
        });
        rocc.setOnAngleChangeListener(new MyRockerView.OnAngleChangeListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void angle(double angle) {
                jd=(int)angle;
                int cj;
                cj=jd*jl;
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        String a= String.valueOf(angle);
                        String ss = "null";
                        String bb= String.valueOf(cj);
                        try {
                            MqttMessage message = new MqttMessage(bb.getBytes());
                            message.setQos(qos);

                            finalClient.publish(topic, message);
                        } catch (MqttException e) {
                            ss=String.valueOf(e);
                        }
                        String finalSs = ss;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tx.setText(finalSs);
                            }
                        });
                    }
                }.start();
                dcca.setText(""+cj);
            }

            @Override
            public void onFinish() {

            }
        });


    }
    public void msqqt(){

    }
public void mqttex(){
    new Thread(){
        @Override
        public void run() {
            super.run();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                }
            });
        }
    }.start();

}
//public void sp(){
//    mSurfaceView = findViewById(R.id.surface_view);
//    IjkMediaPlayer player = new IjkMediaPlayer();
//    mSurfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
//        @Override
//        public void surfaceCreated(@NonNull SurfaceHolder holder) {
//            player.setDisplay(holder);
//            Log.d(TAG, "surfaceCreated: ");
//        }
//
//        @Override
//        public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
//            Log.d(TAG, "surfaceChanged: ");
//        }
//
//        @Override
//        public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
//            Log.d(TAG, "surfaceDestroyed: ");
//        }
//    });
//
//    try {
//        player.setDataSource(url);
////        player.prepareAsync();
//        player.start();
//    } catch (IOException e) {
//        Log.d(TAG, "spddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd: "+e);    }
//
//}
public void web(String weburl){
    videoView.loadUrl(weburl);
    System.out.println(weburl);
    Log.d(TAG, "onClicklllllllllll: "+ weburl);
    //系统默认会通过手机浏览器打开网页，为了能够直接通过WebView显示网页，则必须设置
//                videoView.onResume();
    videoView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
    WebSettings webSettings = videoView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setLoadsImagesAutomatically(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    webSettings.setAllowFileAccess(true);// 设置允许访问文件数据
    webSettings.setSupportZoom(true);
    webSettings.setBuiltInZoomControls(true);
    webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); // 不加载缓存内容
    webSettings.setDomStorageEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setLoadWithOverviewMode(true);

//                WebSettings webSettings = videoView.getSettings();
//                webSettings.setJavaScriptEnabled(true);

    videoView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //使用WebView加载显示url

            view.loadUrl(url);

            //返回true
            return true;
        }

    });

}
}
